//
//  LSWrongCheckViewController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/9/8.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSWrongCheckViewController.h"
#import "LSListenQuesView.h"
#import "LSFollowReadView.h"
#import "LSReadQuesView.h"
#import "LSWrongQuesManager.h"
#import "LSFtpManager.h"

#import "LSListenNewQuesView.h"
#import "LSReadNewQuesView.h"
#import "KZIndexProgressView.h"
#import "LSFollowNewQuesView.h"

@interface LSWrongCheckViewController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource>

@property (nonatomic,strong) UIPageViewController *pageViewController;
@property (nonatomic,strong) NSMutableArray *vcArray;
@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,strong) LSContentVC *pendingViewController;

/**
 进度表示
 */
@property (nonatomic,strong) KZIndexProgressView *progressView;

@end

@implementation LSWrongCheckViewController

- (void)loadWrongBookData {

    [MBProgressHUD showGifAnimationToView:self.view gif:@"LSloading" title:@"试题资源加载中,请稍候..."];
    
    self.wrongQuesModelArr = [NSMutableArray array];
    self.wrongQuesItemArr = [NSMutableArray array];
    
    if ([_item.ResourceFrom isEqualToString:@"A00"]) { //数字化资源库
        
        LSWrongQuesManager *manager = [[LSWrongQuesManager alloc] init];
        NSDictionary *dict = @{@"QuesID":_item.QuesID,@"StageNo":KGetUserDefaults(@"TestLayer")};
        manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
        
        WeakObj(self);
        [manager requestSZTKWithCompltionSuccess:^(LSModelQues *model) {
            NSLog(@"A00");
            [selfWeak.wrongQuesModelArr addObject:model];
            [selfWeak.wrongQuesItemArr addObject:model];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.vcArray = [[NSMutableArray alloc] init];
                for (int i = 0; i<self.wrongQuesModelArr.count; i++) {
                    @autoreleasepool {
                        LSContentVC *vc = [[LSContentVC alloc] init];
                        vc.modelQues = _wrongQuesModelArr[i];
                        vc.resItem = _wrongQuesItemArr[i];
                        [self setUpUIwithFatherView:vc.view];
                        
                        [self.vcArray addObject:vc];
                    }
                }
                
                [self addChildViewController:self.pageViewController];
                [self.view addSubview:self.pageViewController.view];
                [self jumpToControllerIndex:0];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
            
        } failuer:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }];
        
    } else if ([_item.ResourceFrom isEqualToString:@"742"]) { //听说资源库
        //ftp下载数据
        NSString *ftpUrl = _item.FtpUrl;
        NSArray *array = [ftpUrl componentsSeparatedByString:@"/"];
        NSString *currentFileName = [array.lastObject componentsSeparatedByString:@"."].firstObject;
        WeakObj(self);
        LSFtpManager *manager = [[LSFtpManager alloc] init];
        [manager LS_ftpdownloadFileName:currentFileName Path:ftpUrl Success:^(NSDictionary *pathDict, NSArray *names) {
            //            NSLog(@"全部：%@",names);
            //            NSLog(@"获取到数据：%@",pathDict);
            NSDictionary *xmlDic = [NSDictionary dictionaryWithXMLFile:pathDict[@"XML"]];
            LSQuestionType type;
            if ([_item.TypeID isEqualToString:@"SE"]) {
                type = LSListeningTest;
            } else if ([_item.TypeID isEqualToString:@"Sp"] || [_item.TypeID isEqualToString:@"Spn"]) {
                type = LSReadingTest;
            } else {
                type = LSFollowSpeakingTest;
            }
            
            NSString *addressPath = [pathDict[@"XML"] stringByReplacingOccurrencesOfString:[pathDict[@"XML"] componentsSeparatedByString:@"/"].lastObject withString:@""];
            LSModelQues *quesModel = [[LSModelQues alloc] initWithDict:xmlDic Type:type AddressPath:addressPath];
            [selfWeak.wrongQuesModelArr addObject:quesModel];
            [selfWeak.wrongQuesItemArr addObject:quesModel];
            dispatch_async(dispatch_get_main_queue(), ^{
                //self.vcArray = [[NSMutableArray alloc] init];
                for (int i = 0; i<self.wrongQuesModelArr.count; i++) {
                    @autoreleasepool {
                        LSContentVC *vc = [[LSContentVC alloc] init];
                        vc.modelQues = _wrongQuesModelArr[i];
                        vc.resItem = _wrongQuesItemArr[i];
                        [self setUpUIwithFatherView:vc.view];
                        
                        [self.vcArray addObject:vc];
                    }
                }
                
                [self addChildViewController:self.pageViewController];
                [self.view addSubview:self.pageViewController.view];
                [self jumpToControllerIndex:0];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
            
        } failuer:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }];
    }
    
}

- (void)setItem:(LSWrongBookItem *)item {
    _item = item;
    self.allAnswerDict = [NSMutableDictionary dictionary];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    for (NSInteger i = 0; i<item.Answer.count; i++) {
        LSWrongBookAnswer *answer = item.Answer[i];
        [dict setObject:answer.Answer forKey:[NSString stringWithFormat:@"%ld",i+1]];
    }
    [self.allAnswerDict setObject:dict forKey:@"1"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!self.progressView ) {
        KZIndexProgressView *progressView = [[KZIndexProgressView alloc] init];
        progressView.totalIndex = self.wrongQuesItemArr.count;
        progressView.index = _currentIndex+1;
        self.progressView = progressView;
        [self.view addSubview:progressView];
        [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            if (@available(iOS 11.0, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.height.mas_equalTo(48);
                
            } else {
                make.top.equalTo(self.view).offset(0);
                make.height.mas_equalTo(48);
            }
        }];
    }
    
    [self addBYItemviews:@[@"LS-nav_back"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeLeft];
    UIImageView *navImageView = [[UIImageView alloc] init];
    navImageView.image = [UIImage imageNamed:@"LS-content_nav"];
    [self.view addSubview:navImageView];
    [navImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(kNavgationBar);
    }];
    
    self.vcArray = [[NSMutableArray alloc] init];
}

#pragma mark - 其他
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    
    if (_item) {
        self.title = @"详情";
        [self loadWrongBookData];
    } else {
        self.title = @"错题查看";
        [self loadData];
    }
}

- (void)leftItemsAction:(NSInteger)leftIndex {
    
    [self.wrongQuesModelArr removeAllObjects];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
    [self.pageViewController.view removeFromSuperview];
 
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
//    NSString *unzipPath = [NSString stringWithFormat:@"%@%@", NSHomeDirectory(),unzipFilePath];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    if([fileManager removeItemAtPath:unzipPath error:nil] ) {
//        NSLog(@"删除解压文件夹成功");
//    }
}

- (void)loadData {
    
    [MBProgressHUD showGifAnimationToView:self.view gif:@"LSloading" title:@"试题资源加载中,请稍候..."];
    //ftp下载数据
    LSResItem *resItem = _wrongQuesItemArr[_currentIndex];
    NSString *ftpUrl = resItem.FtpUrl;
    NSArray *array = [ftpUrl componentsSeparatedByString:@"/"];
    NSString *currentFileName = [array.lastObject componentsSeparatedByString:@"."].firstObject;
    WeakObj(self);
    LSFtpManager *manager = [[LSFtpManager alloc] init];
    [manager LS_ftpdownloadFileName:currentFileName Path:ftpUrl Success:^(NSDictionary *pathDict, NSArray *names) {
          
            NSDictionary *xmlDic = [NSDictionary dictionaryWithXMLFile:pathDict[@"XML"]];
            LSQuestionType type;
            NSString *typeID= self.typeIDarr[_currentIndex];
            if ([typeID isEqualToString:@"SE"]) {
                type = LSListeningTest;
            } else if ([typeID isEqualToString:@"Sp"] || [typeID isEqualToString:@"Spn"]) {
                type = LSReadingTest;
            } else {
                type = LSFollowSpeakingTest;
            }

            NSString *addressPath = [pathDict[@"XML"] stringByReplacingOccurrencesOfString:[pathDict[@"XML"] componentsSeparatedByString:@"/"].lastObject withString:@""];
            LSModelQues *quesModel = [[LSModelQues alloc] initWithDict:xmlDic Type:type AddressPath:addressPath];
            [selfWeak.wrongQuesModelArr addObject:quesModel];
            dispatch_async(dispatch_get_main_queue(), ^{
                for (int i = 0; i<self.wrongQuesItemArr.count; i++) {
                    @autoreleasepool {
                        LSContentVC *vc = [[LSContentVC alloc] init];
                        vc.resItem = _wrongQuesItemArr[i];
                       // vc.modelQues = _wrongQuesModelArr[i];
                        if (i==0) {
                             [self setUpUIwithFatherView:vc.view Index:i];
                        }
                        [self.vcArray addObject:vc];
                    }
                }

                [self addChildViewController:self.pageViewController];
                [self.view addSubview:self.pageViewController.view];
                [self jumpToControllerIndex:0];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        
    } failuer:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
    }];

}

//进入错题本
- (void)setUpUIwithFatherView:(UIView*)fatherView {
    
    _progressView.totalIndex = 1;
    _progressView.index = 1;
    
    LSModelQues *quesModel = self.wrongQuesModelArr[0];
    NSDictionary *answerDict = self.allAnswerDict[@"1"];
    
    if([_item.TypeID isEqualToString:@"SE"] || [_item.TypeID isEqualToString:@"E"]) {//听力
        
        LSListenNewQuesView *quesView = [[LSListenNewQuesView alloc] initWithFrame:CGRectMake(0,kNavgationBar+48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.answerState = 2;
        quesView.speedLayer = 2;//中速
        quesView.answerDict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
        quesView.model = quesModel;
        [fatherView addSubview:quesView];
        
        [quesView startSource];
        
    } else if ([_item.TypeID isEqualToString:@"Sq"]) {//跟读
        LSFollowNewQuesView *quesView = [[LSFollowNewQuesView alloc] initWithFrame:CGRectMake(0, kNavgationBar+48, kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.answerState = 2;
        quesView.speedLayer = 2;
        quesView.answerDict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
        quesView.model = quesModel;
        [fatherView addSubview:quesView];
        
        [quesView startSource];
        
    } else { //朗读
        
        LSReadNewQuesView *quesView = [[LSReadNewQuesView alloc] initWithFrame:CGRectMake(0,kNavgationBar+48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.answerState = 2;
        quesView.speedLayer = 2;
        quesView.answerDict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
        quesView.model = quesModel;
        [fatherView addSubview:quesView];
    
        [quesView startSource];
        
    }
}

//进入错题查看
- (void)setUpUIwithFatherView:(UIView*)fatherView Index:(NSInteger)index{
    NSNumber *num = self.wrongQuesIndexArr[index];
    NSInteger currentIndex = num.integerValue;
    LSModelQues *quesModel = self.wrongQuesModelArr[index];
    NSString *typeID= self.typeIDarr[index];
    
    NSDictionary *answerDict = [self.allAnswerDict objectForKey:[NSString stringWithFormat:@"%ld",currentIndex+1]];
    
    if([typeID isEqualToString:@"SE"] || [typeID isEqualToString:@"E"]) {//听力
        
        LSListenNewQuesView *quesView = [[LSListenNewQuesView alloc] initWithFrame:CGRectMake(0,kNavgationBar+48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
       // quesView.delegate = self;
        quesView.answerState = 2;
        quesView.speedLayer = _speedLayer;
        quesView.answerDict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
        quesView.model = quesModel;
        [fatherView addSubview:quesView];
        [quesView startSource];
        
    } else if ([typeID isEqualToString:@"Sq"]) {//跟读

        LSFollowNewQuesView *quesView = [[LSFollowNewQuesView alloc] initWithFrame:CGRectMake(0, kNavgationBar+48, kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.answerState = 2;
        quesView.speedLayer = _speedLayer;
        quesView.answerDict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
        quesView.model = quesModel;
        [fatherView addSubview:quesView];
        
        [quesView startSource];

        
    } else { //朗读
        
        LSReadNewQuesView *quesView = [[LSReadNewQuesView alloc] initWithFrame:CGRectMake(0,kNavgationBar+48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.answerState = 2;
        quesView.speedLayer = _speedLayer;
        quesView.answerDict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
        quesView.model = quesModel;
        [fatherView addSubview:quesView];
        
        [quesView startSource];
        
    }
    
}

#pragma mark - pageViewController相关
- (UIPageViewController *)pageViewController {
    if (!_pageViewController) {
        NSDictionary *options = @{UIPageViewControllerOptionInterPageSpacingKey : @(0)};
        // 根据给定的属性实例化UIPageViewController
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                            options:options];
        // 设置UIPageViewController代理和数据源
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        
        // [self jumpToControllerIndex:0];
        
        // 设置UIPageViewController 尺寸
        _pageViewController.view.frame = CGRectMake(0,0, kWidth, kHeight);
        
    }
    return _pageViewController;
}

- (void)jumpToControllerIndex:(NSInteger)index {
    [self.view endEditing:YES];
    
    //BKItemContentViewController *initialViewController = self.vcArray[index];
    LSContentVC * initialViewController = self.vcArray[index];
    
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
    
    [_pageViewController setViewControllers:viewControllers
                                  direction:UIPageViewControllerNavigationDirectionReverse
                                   animated:NO
                                 completion:nil];
}

#pragma mark - pageViewControll Delegate DataSource
#pragma mark - 数组元素值，得到下标值
- (NSUInteger)indexOfViewController:(LSContentVC *)viewController {
    
   // return [self.wrongQuesModelArr indexOfObject:viewController.modelQues];
    
    return [self.wrongQuesItemArr indexOfObject:viewController.resItem];
}


#pragma mark ----- UIPageViewControllerDelegate -----
//开始滚动或翻页的时候触发
- (void)pageViewController:(UIPageViewController *)pageViewController
willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
    _pendingViewController =(LSContentVC*)pendingViewControllers.lastObject;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimePause" object:nil];
    
}

//结束滚动或翻页的时候触发
- (void)pageViewController:(UIPageViewController *)pageViewController
        didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers
       transitionCompleted:(BOOL)completed {
    
    NSInteger index = [self indexOfViewController:_pendingViewController];//滚动结束后的index
    NSLog(@"当前的index是：%ld",(long)index);
    _currentIndex = index;
    self.progressView.index = index+1;
    NSLog(@"%@",self.wrongQuesModelArr);
    if (self.wrongQuesModelArr.count > _currentIndex)  {
        return;
    }
    
    [MBProgressHUD showClearStyleToView:self.view];
   // [MBProgressHUD showGifAnimationToView:self.view gif:@"LSloading" title:@"试题资源加载中,请稍候..."];
    //ftp下载数据
    LSResItem *resItem = _wrongQuesItemArr[_currentIndex];
    NSString *ftpUrl = resItem.FtpUrl;
    NSArray *array = [ftpUrl componentsSeparatedByString:@"/"];
    NSString *currentFileName = [array.lastObject componentsSeparatedByString:@"."].firstObject;
    WeakObj(self);
    LSFtpManager *manager = [[LSFtpManager alloc] init];
    [manager LS_ftpdownloadFileName:currentFileName Path:ftpUrl Success:^(NSDictionary *pathDict, NSArray *names) {
        
        NSDictionary *xmlDic = [NSDictionary dictionaryWithXMLFile:pathDict[@"XML"]];
        LSQuestionType type;
        NSString *typeID= self.typeIDarr[_currentIndex];
        if ([typeID isEqualToString:@"SE"]) {
            type = LSListeningTest;
        } else if ([typeID isEqualToString:@"Sp"] || [typeID isEqualToString:@"Spn"]) {
            type = LSReadingTest;
        } else {
            type = LSFollowSpeakingTest;
        }
        
        NSString *addressPath = [pathDict[@"XML"] stringByReplacingOccurrencesOfString:[pathDict[@"XML"] componentsSeparatedByString:@"/"].lastObject withString:@""];
        LSModelQues *quesModel = [[LSModelQues alloc] initWithDict:xmlDic Type:type AddressPath:addressPath];
        
        [selfWeak.wrongQuesModelArr addObject:quesModel];
        dispatch_async(dispatch_get_main_queue(), ^{
            LSContentVC *vc= selfWeak.vcArray[_currentIndex];
            [selfWeak setUpUIwithFatherView:vc.view Index:_currentIndex];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        
    } failuer:^(NSString *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"error:%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    }];

    
}

#pragma mark ----- UIPageViewControllerDataSource -----
#pragma mark 返回上一个ViewController对象
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    
    [self.view endEditing:YES];
    
    NSUInteger index = [self indexOfViewController:(LSContentVC *)viewController];
    
    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }
    index--;
    // 返回的ViewController，将被添加到相应的UIPageViewController对象上。
    // UIPageViewController对象会根据UIPageViewControllerDataSource协议方法,自动来维护次序
    // 不用我们去操心每个ViewController的顺序问题
    return self.vcArray[index];
    
}

#pragma mark - 返回下一个ViewController对象

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    [self.view endEditing:YES];
    
    NSUInteger index = [self indexOfViewController:(LSContentVC*)viewController];
    
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    
    if (index == [self.wrongQuesItemArr count]) {
        return nil;
    }
    
    return self.vcArray[index];
}

- (void)dealloc {
    NSLog(@"销毁");
}

@end

@implementation LSContentVC

@end
